package br.com.lucasddaniel.merchanmobile.activities;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import br.com.lucasddaniel.merchanmobile.R;
import br.com.lucasddaniel.merchanmobile.adapter.PacotesContratadosAdapter;
import br.com.lucasddaniel.merchanmobile.bean.BluetoothConnector;
import br.com.lucasddaniel.merchanmobile.bean.Device;
import br.com.lucasddaniel.merchanmobile.bean.PacoteArquivoBean;
import br.com.lucasddaniel.merchanmobile.bean.PasseioBean;
import br.com.lucasddaniel.merchanmobile.bean.TuristaBean;
import br.com.lucasddaniel.merchanmobile.dao.ExcessaoBanco;
import br.com.lucasddaniel.merchanmobile.Controller;

import com.datecs.api.printer.Printer;
import com.datecs.api.printer.ProtocolAdapter;
import com.datecs.api.printer.ProtocolAdapter.Channel;

public class ListarPacotesContratadosActivity extends Activity {

    private final Handler mHandler = new Handler();
    private BluetoothConnector mBthConnector;
    private Printer mPrinter;
    private ArrayList<String> listaIdsPacotesComprados;
    private List<PacoteArquivoBean> pacotesDoPasseio = new ArrayList<PacoteArquivoBean>();
    private Integer idTuristaComprador;
    private ProgressDialog mProgressDialog;
    private Button btnTipoMoeda;
    private Float totalGeralReal = Float.valueOf("0.00");
    private Float totalGeralDolar = Float.valueOf("0.00");
    private int tipoMoedaExibido;
    private TextView tvTotalGeral;
    private TextView tvSaldoFinal;
    private EditText edtDesconto;
    private EditText edtSinal;
    private TuristaBean turistaBean;
    private PacotesContratadosAdapter mPacotesContratados;
    private ListView mListView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_listar_pacotes_contratados);

        listaIdsPacotesComprados = getIntent().getStringArrayListExtra("listaIdsPacotesComprados");
        idTuristaComprador = getIntent().getIntExtra("idTuristaComprador", 0);

        mListView = (ListView) findViewById(R.id_activity_listar_pacotes_contratados.listview);
        tvTotalGeral = (TextView) findViewById(R.id_activity_listar_pacotes_contratados.total_geral);
        tvSaldoFinal = (TextView) findViewById(R.id_activity_listar_pacotes_contratados.saldo_final);
        edtDesconto = (EditText) findViewById(R.id_activity_listar_pacotes_contratados.edt_desconto);
        edtSinal = (EditText) findViewById(R.id_activity_listar_pacotes_contratados.sinal);

        edtDesconto.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            	atualizaSaldoFinal();
//                if (count > 0) {
//                    Float desconto = Float.valueOf(s.toString());
//                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });

        edtSinal.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (count > 0) {
                    Float sinal = Float.valueOf(edtSinal.getText().toString());
                    if ( !"".equalsIgnoreCase(edtDesconto.getText().toString())) {
                        tvSaldoFinal.setText("" + ((getTotalGeralNTipoMoeda() - Float.valueOf(edtDesconto.getText().toString())) - sinal));
                    } else {
                        tvSaldoFinal.setText("" + (getTotalGeralNTipoMoeda() - sinal));
                    }
                } else {
                	tvSaldoFinal.setText("" + getTotalGeralNTipoMoeda());
                	atualizaSaldoFinal();
                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });

        try {
            TuristaBean tb = new TuristaBean();
            tb.setId(idTuristaComprador);
            turistaBean = Controller.getInstance().buscarTurista(tb, getApplicationContext());

            List<PacoteArquivoBean> todosPacotes = Controller.getInstance().listarPacotesArquivo();
            for (int i = 0; i < listaIdsPacotesComprados.size(); i++) {
                for (PacoteArquivoBean pabt : todosPacotes) {
                    pabt.setQuantidade(turistaBean.getQuantidade());
                    pabt.setTipoMoeda("Real");
                    Integer ids = Integer.valueOf(listaIdsPacotesComprados.get(i));
                    if (pabt.getId().equals(ids)) {
                        totalGeralReal = (pabt.getPreco() * turistaBean.getQuantidade()) + totalGeralReal;
                        totalGeralDolar = (pabt.getPrecoDolar() * turistaBean.getQuantidade()) + totalGeralDolar;
                        pacotesDoPasseio.add(pabt);
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ExcessaoBanco e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        tvTotalGeral.setText(totalGeralReal + "");

        mPacotesContratados = new PacotesContratadosAdapter(this, R.layout.row_pacotes_contratados, pacotesDoPasseio, turistaBean);
        mListView.setAdapter(mPacotesContratados);
        mListView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> arg0, View arg1, int posicao, long arg3) {
                // EditText edtText = arg1.findViewById( R.id )
            }
        });

        initHeader();

        btnTipoMoeda = (Button) findViewById(R.id_activity_pacotes_contratados.tipo_moeda);
        btnTipoMoeda.setText(getResources().getStringArray(R.array.activity_listar_pacotes_contratados_moeda_pagamento)[0]);
        btnTipoMoeda.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                AlertDialog.Builder alertDialog = new AlertDialog.Builder(ListarPacotesContratadosActivity.this);
                alertDialog.setItems(getResources().getStringArray(R.array.activity_listar_pacotes_contratados_moeda_pagamento), new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dlg, int item) {
                        btnTipoMoeda.setText(getResources().getStringArray(R.array.activity_listar_pacotes_contratados_moeda_pagamento)[item]);
                        tipoMoedaExibido = item;
                        trocaMoeda();
                    }
                });
                alertDialog.show();
            }
        });

        Float desc = Float.valueOf("0.00");
        Float sinal = Float.valueOf("0.00");
        Float totalGeralTmp = getTotalGeralNTipoMoeda();
        if (edtDesconto.getText().toString() != null && !"".equalsIgnoreCase(edtDesconto.getText().toString())) {
            desc = Float.valueOf(edtDesconto.getText().toString());
        }
        if (edtSinal.getText().toString() != null && !"".equalsIgnoreCase(edtSinal.getText().toString())) {
            sinal = Float.valueOf(edtSinal.getText().toString());
        }

        tvSaldoFinal.setText((totalGeralTmp - desc - sinal) + "");

        Button imprimirCupom = (Button) findViewById(R.id_activity_pacotes_contratados.imprimir);
        imprimirCupom.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                final PasseioBean passeio = new PasseioBean();
                try {
                    if (!"".equalsIgnoreCase(tvTotalGeral.getText().toString())) {
                        passeio.setTotalGeral(Float.valueOf(tvTotalGeral.getText().toString()));
                    }
                    if (!"".equalsIgnoreCase(edtDesconto.getText().toString())) {
                        passeio.setDesconto(Float.valueOf(edtDesconto.getText().toString()));
                    }
                    if (!"".equalsIgnoreCase(edtSinal.getText().toString())) {
                        passeio.setSinal(Float.valueOf(edtSinal.getText().toString()));
                    }
                    if (!"".equalsIgnoreCase(tvSaldoFinal.getText().toString())) {
                        passeio.setSaldoFinal(Float.valueOf(tvSaldoFinal.getText().toString()));
                    }
                    passeio.setNomeTurista(turistaBean.getNome());
                    passeio.setNomeGuia(turistaBean.getOperador());
                    passeio.setNomePousada(turistaBean.getPousada());
                    if (tipoMoedaExibido == 0) {
                        passeio.setTipoDeMoeda("Real");
                    } else {
                        passeio.setTipoDeMoeda("Dolar");
                    }
                    passeio.setPacotes(pacotesDoPasseio);
                    passeio.setId(Controller.getInstance().inserePasseio(passeio, ListarPacotesContratadosActivity.this));
                } catch (ExcessaoBanco e) {
                    e.printStackTrace();
                }
                new Thread() {
                    @Override
                    public void run() {
                        showProgress("Imprimindo");
                        doPrintImage();
                        doPrintText(passeio, turistaBean);
                        dismissProgress();
                        Intent i = new Intent(getApplicationContext(), MenuActivity.class);
                        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(i);
                    }
                }.start();
            }
        });

    }

    private Float getTotalGeralNTipoMoeda() {
        Float totalGeralTmp = Float.valueOf("0.00");
        if (tipoMoedaExibido == 0) { // real R$
            totalGeralTmp = totalGeralReal;
        } else { // Dolar $
            totalGeralTmp = totalGeralDolar;
        }
        return totalGeralTmp;
    }

    private void trocaMoeda() {
        mPacotesContratados.setTipoMoedaExibido(tipoMoedaExibido);
        mPacotesContratados.notifyDataSetChanged();
        atualizaTotalGeral();
        atualizaSaldoFinal();
    }

    private void atualizaTotalGeral() {
    	tvTotalGeral.setText("" + getTotalGeralNTipoMoeda());
    }
    
    private void atualizaSaldoFinal() {
        if (!"".equalsIgnoreCase(edtDesconto.getText().toString()) && !"".equalsIgnoreCase(edtSinal.getText().toString())) {
            tvSaldoFinal.setText("" + ((getTotalGeralNTipoMoeda() - Float.valueOf(edtDesconto.getText().toString())) - Float.valueOf(edtSinal.getText().toString())));
        } else if (!"".equalsIgnoreCase(edtDesconto.getText().toString())) {
            tvSaldoFinal.setText("" + (getTotalGeralNTipoMoeda() - Float.valueOf(edtDesconto.getText().toString())));
        } else if (!"".equalsIgnoreCase(edtSinal.getText().toString())) {
            tvSaldoFinal.setText("" + (getTotalGeralNTipoMoeda() - Float.valueOf(edtSinal.getText().toString())));
        } else {
            tvSaldoFinal.setText("" + getTotalGeralNTipoMoeda());
        }
    }
    
    public void updateTotais(List<PacoteArquivoBean> listPacotesBean) {
        totalGeralReal = Float.valueOf("0.00");
        totalGeralDolar = Float.valueOf("0.00");
        for (PacoteArquivoBean pabt : listPacotesBean) {
            totalGeralReal = (pabt.getPreco() * pabt.getQuantidade()) + totalGeralReal;
            totalGeralDolar = (pabt.getPrecoDolar() * pabt.getQuantidade()) + totalGeralDolar;
            if (tipoMoedaExibido == 0) { // real R$
                pabt.setTotal(totalGeralReal);
                pabt.setTipoMoeda("Real");
            } else { // Dolar $
                pabt.setTotal(totalGeralDolar);
                pabt.setTipoMoeda("Dolar");
            }
        }
        if (!"".equalsIgnoreCase(edtDesconto.getText().toString())) {
            tvTotalGeral.setText("" + (getTotalGeralNTipoMoeda() - Float.valueOf(edtDesconto.getText().toString())));
        } else {
            tvTotalGeral.setText("" + getTotalGeralNTipoMoeda());
        }
        atualizaSaldoFinal();
    }

    private void initHeader() {
        TextView nome = (TextView) findViewById(R.id_activity_listar_pacotes_contratados.nome);
        TextView pousada = (TextView) findViewById(R.id_activity_listar_pacotes_contratados.pousada);
        TextView operador = (TextView) findViewById(R.id_activity_listar_pacotes_contratados.operador);
        nome.setText(turistaBean.getNome());
        pousada.setText(turistaBean.getPousada());
        operador.setText(turistaBean.getOperador());
    }

    private final Thread mConnectThread = new Thread() {
        @Override
        public void run() {
            Looper.prepare();
            showProgress("conectando...");
            Device device = null;
            try {
                device = Controller.getInstance().buscarDevicePrincipal(getApplicationContext());
            } catch (ExcessaoBanco e) {
                e.printStackTrace();
                dismissProgress();
                showProgress(e.getMessage());
            }
            Log.d("BLUETOOTH", device.getEndereco());
            connectBth(device.getEndereco());
            dismissProgress();
            Looper.loop();
        }

        void connectBth(String address) {

            try {
                mBthConnector = BluetoothConnector.getConnector(ListarPacotesContratadosActivity.this);
                mBthConnector.connect(address);
                mPrinter = getPrinter(mBthConnector.getInputStream(), mBthConnector.getOutputStream());
            } catch (IOException e) {
                Log.d("BLUETOOTH", e.getMessage());
                e.printStackTrace();
                error(R.drawable.bluetooth, e.getMessage());
                return;
            }
        }

        Printer getPrinter(InputStream in, OutputStream out) throws IOException {
            ProtocolAdapter adapter = new ProtocolAdapter(in, out);
            Printer printer = null;

            if (adapter.isProtocolEnabled()) {
                Channel channel = adapter.getChannel(ProtocolAdapter.CHANNEL_PRINTER);
                InputStream newIn = channel.getInputStream();
                OutputStream newOut = channel.getOutputStream();
                printer = new Printer(newIn, newOut);
            } else {
                printer = new Printer(in, out);
            }

            return printer;
        }
    };

    @Override
    protected void onStart() {
        super.onStart();
        mConnectThread.start();
    }

    @Override
    protected void onStop() {
        super.onStop();

        if (mBthConnector != null) {
            try {
                mBthConnector.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void showProgress(final String text) {
        mHandler.post(new Runnable() {
            public void run() {
                mProgressDialog = ProgressDialog.show(ListarPacotesContratadosActivity.this, "Aguarde um momento...", text, true);
            }
        });
    }

    private void dismissProgress() {
        mHandler.post(new Runnable() {
            public void run() {
                mProgressDialog.dismiss();
            }
        });
    }

    private void doPrintText(PasseioBean passeio, TuristaBean turista) {
        StringBuffer sb = new StringBuffer();
        Calendar c = Calendar.getInstance();
        // sb.append("{reset}{center}{w}{h}IN BÚZIOS{br}");
        // sb.append("{reset}{center}{w}RECEPTIVO{br}");
        sb.append("{reset}Guia: " + Controller.getInstance().getResponsavelLogado().getLogin() + "{br}");
        sb.append("{reset}Voucher: {b}" + passeio.getId() + "{br}");
        sb.append("{reset}Fone: +55 22-2623-6033{br}");
        sb.append("{reset}Nextel: 36676*25{br}");
        SimpleDateFormat sdfData = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        sb.append("{reset}Data: " + sdfData.format(c.getTime()) + "{br}");
        sb.append("{reset}Nome: {b}" + passeio.getNomeTurista() + "{br}");
        sb.append("{reset}Pousada: " + passeio.getNomePousada() + "{br}");
        sb.append("{reset}--------------------------------{br}");
        for (PacoteArquivoBean pac : passeio.getPacotes()) {
            sb.append("{reset}{b}" + pac.getNome() + "{br}");
            // sb.append("{reset}{b}Data: 03/10/2012 Hora: 08:00{br}{br}");
            sb.append("{reset}{b}Hora: " + sdfData.format(pac.getDataHoraSaida()) + "{br}");
            sb.append("{reset}Qtd: " + pac.getQuantidade() + "{br}");
            try {
				for (PacoteArquivoBean pc : Controller.getInstance().listarPacotesArquivo()) {
					if (pac.getNome().equalsIgnoreCase(pc.getNome())) {
						sb.append("{reset}Obs: " + pc.getTransporte() + "{br}{br}");
						break;
					}
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (ExcessaoBanco e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
        }
        sb.append("{reset}--------------------------------{br}");
        sb.append("{reset}{b}Valor: " + passeio.getTotalGeral() +" -> " + passeio.getTipoDeMoeda()  + "{br}");
        if (passeio.getSinal() == null) {
        	sb.append("{reset}{b}Desconto: 0{br}");
        } else {
        	sb.append("{reset}{b}Desconto: " + passeio.getDesconto() + "{br}");
        }
        if (passeio.getSinal() == null) {
        	sb.append("{reset}{b}Sinal: 0" + "{br}");
        } else {
        	sb.append("{reset}{b}Sinal: "+ passeio.getSinal() + "{br}");
        }
        sb.append("{reset}{b}Saldo: " + passeio.getSaldoFinal() + "{br}{br}");
//        sb.append("{reset}{b}Obs: " + turista.getObservacao() + "{br}");

        try {
            mPrinter.reset();
            mPrinter.printTaggedText(sb.toString());
            mPrinter.feedPaper(110);
        } catch (IOException e) {
            e.printStackTrace();
            error(R.drawable.printer_icon, "Falha ao imprimir o cupom. " + e.getMessage());
        }
    }

    private void doPrintImage() {
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
        final int width = bitmap.getWidth();
        final int height = bitmap.getHeight();
        final int[] argb = new int[width * height];
        bitmap.getPixels(argb, 0, width, 0, 0, width, height);

        try {
            mPrinter.reset();
            mPrinter.printImage(argb, width, height, Printer.ALIGN_CENTER, true);
        } catch (IOException e) {
            error(R.drawable.printer_icon, "Falha ao imprimir o cupom. " + e.getMessage());
        }
    }

    private void error(final int resIconId, final String message) {
        mHandler.post(new Runnable() {
            public void run() {
                AlertDialog dlg = new AlertDialog.Builder(ListarPacotesContratadosActivity.this).setTitle("Error").setMessage(message).create();
                dlg.setIcon(resIconId);
                dlg.setOnDismissListener(new OnDismissListener() {
                    public void onDismiss(DialogInterface dialog) {
                        ListarPacotesContratadosActivity.this.finish();
                    }
                });
                dlg.show();
            }
        });
    }
}
